package search;

/**
 * Created by IntelliJ IDEA.
 * User: 杰哥
 * Date: 2020/4/10
 * Time: 8:51
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1,8,10,89,100,200};
        int index = binarySearch(arr,0,arr.length-1,8);
        System.out.println(index);
    }

    /**
     * 二分查找，这里只针对从小到大的有序数组
     * @param arr
     * @param left 左边索引
     * @param right 右边索引
     * @param findVal 要查找的值
     * @return
     */
    public static int binarySearch(int[] arr, int left, int right, int findVal) {
        if(left > right) { //说明没有找到，返回-1
            return -1;
        }
        int mid = (left + right) / 2;
        if(findVal > arr[mid]) { //右递归
            return binarySearch(arr, mid + 1, right, findVal);
        }else if(findVal < arr[mid]) {
            return binarySearch(arr, left, mid - 1, findVal);
        }else {
            return mid;
        }
    }

}
